var config = require("../../config.js")
var util = require("../../utils/MD5.js");
var date = new Date();
const app = getApp();
const common = require('../../common/js/common.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        faceList: [],
        memberNumber: "0", // 会员编号
        memberInfo: {},
        editFace: "",
        editName: "",
        editSex: 1,
        editTel: "",
        sex: 1,
        mebbirth: "请选择会员生日",
        mebClass: false,
        editTag: "",
        editFace: "",
        C_SHOP_NO: "", // 店铺编号
        faceid: "",
        opInfo: {}, // 
        startPage: 1,
        pageSize: 20,
        pWidth: 0,
        options: {},
        startDate: "1900-01-01",
        endDate: "",
        region: ['广东省', '广州市', '海珠区'],
        hasRegion: false,
    },

    /**
     * 生命周期函数--监听页面加载
     * editType 1 -> 从会员列表查看会员，编辑的时候过来
     */
    onLoad: function(options) {
        console.log('options-----------')
        console.log(options)
        options.editType = 1;
        this.data.options = options;
        this.setData({
            edit: options.edit || null,
            options: options,
            filePath: config.FilePath,
            endDate: date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
        })
        wx.getSystemInfo({
            success: res => {
                this.setData({
                    pwidth: res.screenWidth / 4
                })
            },
        });

        wx.getSystemInfo({
            success: res => {
                this.setData({
                    pWidth: res.windowWidth / 3
                })
            },
        })

        wx.getStorage({
            key: 'shop_data',
            success: res => {
                this.data.shopInfo = res.data;
            },
        })

        wx.getStorage({
            key: 'OP_INFO',
            success: res => {
                this.data.opInfo = res.data;
            },
        })

        this.getShopNo();
        common.getMemberLevel(this)
    },
    // 选择会员等级
    memberLevelChange(e){
        console.log(this.data.memberLevel)
        console.log(e.detail.value)
        this.setData({
            memberLevelIndex: e.detail.value,
            n_mg_id: this.data.memberLevel[e.detail.value].N_MG_ID
        })
    },
    hideDialog() {
        this.setData({
            err: false,
        })
    },

    getShopNo() {
        wx.getStorage({
            key: 'C_SHOP_NO',
            success: res => {
                this.data.ShopNo = res.data;
                this.data.C_SHOP_NO = res.data;
                if (this.data.options.editType == "1") {
                    wx.getStorage({
                        key: 'member_data',
                        success: res => {
                            var member = res.data;
                            // C_MB_SEX
                            var sex = 1;
                            this.data.faceid = res.data.N_Id;
                            var editName = member.username ? member.username : member.C_MB_NAME;
                            if (member.gender) {
                                sex = member.gender != 3 ? member.gender : 1;
                            }
                            if (!member.C_MB_PIC) {
                                if (member.wdzpicurllast.indexOf("ovopark") != -1) {
                                    member.C_MB_PIC = member.wdzpicurllast;
                                } else {
                                    member.C_MB_PIC = config.FilePath + member.wdzpicurllast;
                                }
                            } else {
                                if (member.C_MB_PIC.indexOf("ovopark") == -1) {
                                    if (member.C_MB_PIC.indexOf("upfile") == -1) {
                                        member.C_MB_PIC = config.FilePath + member.C_MB_PIC;
                                        this.data.editFace = member.C_MB_PIC;
                                    }
                                }
                            }

                            if (member.C_MB_SEX == "男") {
                                sex = 1;
                            } else {
                                sex = 2
                            }

                            var mebbirth = "请选择会员生日";
                            var mebClass = false;
                            if (member.D_MB_BIRTHDAY) {
                                mebbirth = member.D_MB_BIRTHDAY;
                                mebClass = true;
                            }

                            this.getFace();
                            this.setData({
                                memberNumber: member.C_MB_NO,
                                editTel: member.C_MB_PHONE,
                                mebClass,
                                mebbirth,
                                sex,
                                editName,
                                editSex: sex,
                                memberInfo: member
                            })
                            console.log(this.data.memberInfo)
                        },
                        fail: () => {
                            this.getFace();
                        }
                    })
                }
            },
        })
    },

    setName(ev) {
        this.data.memberInfo.C_MB_NAME = ev.detail.value;
        this.setData({
            memberInfo: this.data.memberInfo,
            editName: ev.detail.value
        })
    },

    setTel(ev) {
        this.data.memberInfo.C_MB_PHONE = ev.detail.value;
        this.setData({
            memberInfo: this.data.memberInfo,
            editTel: ev.detail.value
        })
    },

    saveSrc(ev) {
        var src = ev.currentTarget.dataset.sr;;
        var id = ev.currentTarget.dataset.id;
        // 设置提交的会员头像
        this.data.editFace = src;
        if (src.indexOf("ovopark") != -1) {
            this.data.memberInfo.C_MB_PIC = src;
        } else {
            this.data.memberInfo.C_MB_PIC = config.FilePath + src;
        }

        this.setData({
            memberInfo: this.data.memberInfo,
            chooseFace: false,
            faceid: id
        });
    },

    cancelChoose() {
        this.setData({
            chooseFace: false,
            choose: false,
        })
    },

    chooseImg() {
        this.setData({
            choose: true
        })
    },

    lower: function(e) {
        if (this.data.startPage < this.data.PageCount) {
            this.data.startPage++;
            this.getFace();
        }
    },

    changeSex(ev) {
        this.setData({
            sex: ev.currentTarget.dataset.i
        })
        this.data.editSex = this.data.sex;
    },

    chooseTag(ev) {
        wx.navigateTo({
            url: '/pages/memberTag/memberTag?tag=' + ev.currentTarget.dataset.t,
        })
    },

    getFace() {
        // this.data.C_SHOP_NO = "100010";
        if (!this.data.faceid) {
            this.data.faceid = 0;
        }
        var str = "pageindex&pagesize&mebno&times&IsMinute&ShopNo&faceid=" + this.data.startPage + "*" + this.data.pageSize + "*" + this.data.memberNumber + "*1000*0*" + this.data.C_SHOP_NO + "*" + this.data.faceid;
        var md5 = util.md5(str);
        var data = {
            bNo: 1710,
            pageindex: this.data.startPage,
            pagesize: this.data.pageSize,
            mebno: this.data.memberNumber,
            times: 1000,
            IsMinute: 0,
            ShopNo: this.data.C_SHOP_NO,
            faceid: this.data.faceid,
            MD5: md5.toUpperCase()
        }

        wx.request({
            url: config.requestUrl,
            data,
            success: res => {
                if (res.data.code === "100") {
                    if (this.data.PageCount == 0) {
                        this.data.PageCount = res.data.PageCount;
                    }
                    for (var i = 0; i < res.data.memberList.length; i++) {
                        res.data.memberList[i].width = 0;
                        res.data.memberList[i].height = 0;
                        if (res.data.memberList[i].wdzpicurllast) {
                            if (res.data.memberList[i].wdzpicurllast.indexOf("ovopark") < 0) {
                                res.data.memberList[i].wdzpicurl = config.FilePath + res.data.memberList[i].wdzpicurllast;
                            } else {
                                res.data.memberList[i].wdzpicurl = res.data.memberList[i].wdzpicurllast;
                            }
                        }
                        if (res.data.memberList[i].wdzpicurl) {
                            if (res.data.memberList[i].wdzpicurl.indexOf("ovopark") < 0) {
                                res.data.memberList[i].wdzpicurl = config.FilePath + res.data.memberList[i].wdzpicurl;
                            }
                        }
                        this.data.faceList.push(res.data.memberList[i])
                    }
                    this.setData({
                        faceList: this.data.faceList
                    })
                }
            }
        })
    },

    resetSize(ev) {
        var i = ev.currentTarget.dataset.i;
        this.data.faceList[i].height = this.data.pWidth;
        this.setData({
            faceList: this.data.faceList
        })
    },

    checkTel(ev) {
        if (!/1\d{10}/g.test(ev.detail.value)) {
            wx.showModal({
                title: '提示',
                content: '请填写正确的手机号',
                showCancel: false,
            })
        }
    },

    showFace(ev) {
        var src = ev.currentTarget.dataset.s;
        wx.previewImage({
            urls: [src],
        })
    },

    setMemberBirth(ev) {
        this.setData({
            mebbirth: ev.detail.value,
            mebClass: true,
        })
    },
    //  选择地址
    bindRegionChange(e) {
        this.setData({
            region: e.detail.value,
            hasRegion: true
        })
    },
    // 设置详细地址
    setAddress(e) {
        this.setData({
            c_address: e.detail.value
        })
    },
    // 新增会员
    saveMemberInfo(callback) {
        if (this.data.editName.length <= 0) {
            this.setData({
                err: true,
                errMessage: "请填写会员称呼"
            });
            return
        }

        if (!/1\d{10}/g.test(this.data.editTel)) {
            wx.showModal({
                title: '提示',
                content: '请填写正确的手机号',
                showCancel: false,
            })
            return;
        }

        if (this.data.mebbirth != "请选择会员生日") {
            if (!this.data.mebbirth) {
                wx.showModal({
                    title: '提示',
                    content: '请选择会员生日',
                    showCancel: false,
                })
                return;
            }
        } else {
            this.data.mebbirth = "";
        }
       
        if (!this.data.edit){ //新增
            if (!this.data.hasRegion) {
                wx.showModal({
                    title: '提示',
                    content: '请选择地址',
                    showCancel: false,
                })
                return;
            }
            if (!this.data.c_address) {
                wx.showModal({
                    title: '提示',
                    content: '请填写详细地址',
                    showCancel: false,
                })
                return;
            }
            if (!this.data.n_mg_id) {
                wx.showModal({
                    title: '提示',
                    content: '请选择会员等级',
                    showCancel: false,
                })
                return;
            }
        }
       

        wx.showLoading({
            title: '提交中...',
        });

        const str = "name&sex&phone&tagname&headimg&mebno&ShopNo&isweburl&faceid&openid&xcxopenid&shopname&opname&opid"
        let params = {
            bNo: '1709b',
            name: this.data.editName,
            sex: this.data.editSex,
            phone: this.data.editTel,
            tagname: this.data.editTag,
            headimg: this.data.editFace,
            mebno: this.data.memberNumber,
            ShopNo: this.data.C_SHOP_NO,
            isweburl: 0,
            mebbirth: this.data.mebbirth,
            faceid: this.data.faceid,
            openid: "",
            xcxopenid: "",
            shopname: this.data.shopInfo.c_name,
            opname: this.data.opInfo.c_name,
            opid: this.data.opInfo.n_ss_id,
            c_province: this.data.hasRegion ? this.data.region[0] : '',
            c_city: this.data.hasRegion ? this.data.region[1] : '',
            c_area: this.data.hasRegion ? this.data.region[2] : '',
            c_address: this.data.c_address ? this.data.c_address : '',
            n_mg_id: this.data.n_mg_id ? this.data.n_mg_id : '',
        }
        app.apiGet(str, params, (res) => {
            console.log(res)
            wx.showToast({
                title: this.data.isMember ? "保存成功" : "添加成功",
                icon: "success",
                mask: true,
                success: () => {
                    setTimeout(() => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }, 1000)
                }
            })
        },(err) => {
            wx.showToast({
                title: err.msg,
                icon: "none",
            })
        },() => {
            wx.hideLoading()
        })
    },
    // 新增会员
    saveMemberInfo1() {
        if (this.data.editName.length <= 0) {
            this.setData({
                err: true,
                errMessage: "请填写会员称呼"
            });
            return
        }

        if (!/1\d{10}/g.test(this.data.editTel)) {
            wx.showModal({
                title: '提示',
                content: '请填写正确的手机号',
                showCancel: false,
            })
            return;
        }

        if (this.data.mebbirth != "请选择会员生日") {
            if (!this.data.mebbirth) {
                wx.showModal({
                    title: '提示',
                    content: '请选择会员生日',
                    showCancel: false,
                })
                return;
            }
        } else {
            this.data.mebbirth = "";
        }
        if (!this.data.hasRegion){
            wx.showModal({
                title: '提示',
                content: '请选择地址',
                showCancel: false,
            })
            return;
        }
        if (!this.data.c_address){
            wx.showModal({
                title: '提示',
                content: '请填写详细地址',
                showCancel: false,
            })
            return;
        }

        wx.showLoading({
            title: '提交中...',
        });
        var str = "name&sex&phone&tagname&headimg&mebno&ShopNo&isweburl&faceid&openid&xcxopenid&shopname&opname&opid=" + this.data.editName + "*" + this.data.editSex + "*" + this.data.editTel + "*" + this.data.editTag + "*" + this.data.editFace + "*" + this.data.memberNumber + "*" + this.data.C_SHOP_NO + "*0*" + this.data.faceid + "***" + this.data.shopInfo.c_name + "*" + this.data.opInfo.c_name + "*" + this.data.opInfo.n_ss_id;
        var md5 = util.md5(str);
        var data = {
            bNo: 1709,
            name: this.data.editName,
            sex: this.data.editSex,
            phone: this.data.editTel,
            tagname: this.data.editTag,
            headimg: this.data.editFace,
            mebno: this.data.memberNumber,
            ShopNo: this.data.C_SHOP_NO,
            isweburl: 0,
            mebbirth: this.data.mebbirth,
            faceid: this.data.faceid,
            openid: "",
            xcxopenid: "",
            shopname: this.data.shopInfo.c_name,
            opname: this.data.opInfo.c_name,
            opid: this.data.opInfo.n_ss_id,
            MD5: md5.toUpperCase()
        }

        wx.request({
            url: config.requestUrl,
            data,
            success: res => {
                if (res.data.code === "100") {
                    wx.showToast({
                        title: this.data.isMember ? "保存成功" : "添加成功",
                        icon: "success",
                        mask: true,
                        success: () => {
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 1
                                })
                            }, 1000)
                        }
                    })
                } else if (res.data.code === "-102") {
                    wx.showModal({
                        title: '提示',
                        content: res.data.msg,
                        showCancel: false,
                    })
                    wx.hideLoading()
                } else {
                    this.setData({
                        err: true,
                        errMessage: "添加失败，请重试"
                    })
                    wx.hideLoading()
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.getStorage({
            key: 'choose_member_tag',
            success: res => {
                this.data.memberInfo.C_MemberTag = res.data.replace(/\,/g, "  ");
                this.setData({
                    editTag: res.data,
                    memberInfo: this.data.memberInfo,
                    tag: res.data
                })
            },
        })

        wx.getStorage({
            key: 'photo_src',
            success: res => {
                this.data.memberInfo.C_MB_PIC = config.FilePath + res.data
                this.setData({
                    memberInfo: this.data.memberInfo,
                    editFace: res.data
                })
                wx.removeStorage({
                    key: 'photo_src',
                })
            },
        })
    },

    showList() {
        wx.showActionSheet({
            itemList: ['拍照', '从相册中选择', "从人脸库选择"],
            success: res => {
                if (res.tapIndex == 0) {
                    wx.navigateTo({
                        url: '/pages/cameraTest/cameraTest',
                    })
                } else if (res.tapIndex == 1) {
                    this.chooseImages()
                } else if (res.tapIndex == 2) {
                    this.setData({
                        chooseFace: true,
                        choose: false,
                    })
                }
            }
        })
    },

    chooseImages() {
        wx.chooseImage({
            count: 1,
            sizeType: ["compressed"],
            sourceType: ["album"],
            success: res => {
                this.uploadImages(res.tempFilePaths[0])
            },
        })
    },

    uploadImages(url) {
        wx.showLoading({
            title: '正在上传',
        })
        wx.uploadFile({
            url: config.requestUrl + "?bNo=1907",
            filePath: url,
            name: 'file',
            formData: {
                filepath: encodeURI(url)
            },
            success: res => {
                if (res.data) {
                    var data = res.data.replace(/\(|\)/g, "");
                    var data2 = JSON.parse(data);
                    this.data.memberInfo.C_MB_PIC = config.FilePath + data2.filepath;
                    this.setData({
                        memberInfo: this.data.memberInfo,
                        editFace: data2.filepath
                    })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '上传失败',
                        showCancel: false
                    })
                }
            },
            fail: msg => {
                wx.showModal({
                    title: '提示',
                    content: '上传失败',
                    showCancel: false
                })
            },
            complete: () => {
                wx.hideLoading()
            }
        })
    },
})